import axios from 'axios'
import store from 'common/src/store/index'
import { logout, getSSOLogoutUrl } from 'common/src/api/session'

import {
  Loading,
  MessageBox
} from 'element-ui'

const CancelToken = axios.CancelToken
import FetchUtils from './fetchUtils'

/**
 *
 * @returns
 * 由于商演环境和生产环境实现sso登录，因此存取的sessonid都属于session级别
 * 待优化
 */
function getToken() {
  if (['1.tongji.edu.cn', '122.112.219.67:30669'].indexOf(window.location.host) > -1) {
    return sessionStorage.getItem('sessionid') || ''
  } else {
    return localStorage.getItem('sessionid') || ''
  }
}

// 创建axios实例
// var gateway_ip_port= prosess.ENV.gateway_ip_port;
const service = axios.create({
  // baseURL: process.env.BASE_API, // api 的 base_url
  baseURL: '/release',
  timeout: 60000 * 2 // 请求超时时间
})
const FU = new FetchUtils()
function declareProjId(config) {
  const url = config.url
  const cultureserviceReg = /^\/api\/(.+service)\/.+$/i
  const currentUser = store.state.session.mockUser ? store.state.session.mockUser : store.state.session.user
  if (currentUser) {
    const currentManageDptId = currentUser.currentManageDptId
    const currentRole = currentUser.currentRole
    if (currentRole == 1) {
      if (cultureserviceReg.test(url)) {
        if (config.data && config.data.hasOwnProperty('projId')) {
          config.data.projId = currentManageDptId
        }
        if (
          config.data &&
          config.data.hasOwnProperty('managerDeptId') &&
          (config.data.managerDeptId == null || config.data.managerDeptId == '')
        ) {
          config.data.managerDeptId = currentManageDptId
        }
        if (
          /^\/api\/(.+service)\/.*\?(.+=.*&)*(projId|managerDeptId)=([^&]*)(&.+=.*)*$/i.test(
            url
          )
        ) {
          const paramValue = RegExp.$4
          const paramName = RegExp.$3
          config.url = url.replace(
            `${paramName}=${paramValue}`,
            `${paramName}=${currentManageDptId}`
          )
        }
      }
    }
  }
}
service.loadingInstanceCount = 0
// 发现连接成功

function closeLoding() {
  if (service.loadingInstanceCount > 0) {
    service.loadingInstanceCount = service.loadingInstanceCount - 1
  }
  if (service.loadingInstanceCount === 0 && service.loadingInstance1) {
    service.loadingInstance1.close()
  }
}

/**
 * 退出操作
 * 调用退出接口
 * 清理store中存储的用户登录信息
 */
function userLogout(Router) {
  const userType = store.getters.getUserType()
  const user = JSON.parse(localStorage.getItem('user'))
  const sessionid = store.getters.getSessionId()
  logout({
    sessionid,
    uid: user.uid
  }).then(res => {
    if (res.code == 200) {
      store.commit('clear_login_info')
      store.commit('clear_tab_info')
      if (userType && userType == 3) {
        // debugger
        Router.replace('/locallogin')
      } else {
        if (store.state.is_sso_saml) {
          window.location.href = store.state.ssologout
          return
        }
        if (user && user.uid) {
          // getSSOLogoutUrl(user.uid)
          window.location.href = store.state.ssourl
        } else {
          showMessageBox('参数错误')
        }
        // window.location.href = store.state.ssologout
      }
    }
  })
}

function showMessageBox(message, statusCode, detail, istimeOut) {
  if (window.isSessionDialogOut !== true) {
    window.isSessionDialogOut = true // 解决会弹出多个过期提示问题
    window.vueApp.showMsgBox({
      message: message || '系统故障，请联系管理员！',
      detail: detail,
      istimeOut: istimeOut,
      callback: () => {
        window.isSessionDialogOut = false
      }
    })
    // MessageBox.alert(message, '提示', {
    //     confirmButtonText: '确定',
    //     closeOnClickModal: false,
    //     type: statusCode == 500 ? 'error': 'info',
    //     callback: ()=>{
    //         window.isSessionDialogOut = false;
    //     }
    // });
  }
}

function checkResFile(val) {
  // 后续可补充
  var reg = new RegExp('^application/(zip|msword|pdf)')
  return reg.test(val)
}

// 自定义方法
service.initFun = function (VM, router) {
  // request拦截器
  service.interceptors.request.use(
    config => {
      let cancel
      config.cancelToken = new CancelToken(function executor(c) {
        cancel = c
      })

      if (config.url.indexOf('liao/') > -1) {
        config.baseURL = ''
      }
      if (config.url.indexOf('yuhang/') > -1) {
        config.baseURL = ''
      }
      if (config.url.indexOf('dongWG/') > -1) {
        config.baseURL = ''
      }

      declareProjId(config)
      FU.request(config.url, cancel)
      if (_.lowerCase(config.method) === 'get') {
        if (!config.params) {
          config.params = {}
        }
        config.params._t = new Date().getTime()
      }
      if (config.showMask !== false) {
        service.loadingInstance1 = Loading.service({
          fullscreen: true,
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(255, 255, 255, .48)',
          customClass: 'self-loading'
        })
        service.loadingInstanceCount++
      }
      config.headers['X-Token'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
      return config
    },
    error => {
      closeLoding()
      Promise.reject(error)
    }
  )

  // respone拦截器
  service.interceptors.response.use(
    response => {
      response.status && FU.response(response.config.url)
      closeLoding()
      const rspData = response.data

      // console.log('response');
      // console.log(response);
      // console.log(rspData);
      if (
        rspData.code &&
        rspData.code !== 200 &&
        rspData.code !== 302 &&
        rspData.code !== 305 &&
        rspData.code !== 308 &&
        rspData.code !== 307 &&
        rspData.code !== 311 &&
        rspData.code !== 312 &&
        rspData.code !== 313
      ) {
        showMessageBox(rspData.msg, rspData.code, rspData.data)
        return Promise.reject(`response code [${rspData.code}] error`)
      }
      return rspData
    },
    error => {
      closeLoding()
      const rsp = error.response
      rsp.status && FU.response(rsp.config.url)
      if (rsp && rsp.status === 401) {
        /**
               * 需求变化调整
               * 用户登录超时，直接进入登录页
               */
        userLogout(router)
        /**
               * 原始需求
               * 登录超时，跳转首页后需要点击确认才能进入sso登录页
               */
      } else {
        let message = error.message
        let tip = null
        let statusCode = 400
        let istimeOut = false
        if (rsp) {
          if (rsp.data) {
            const _data = rsp.data
            message = _data.message ? _data.message : _data
            tip = _data.tip
            statusCode = rsp.status
          }
          if (tip == null && statusCode != 400 && rsp.statusText) {
            tip = rsp.statusText
          }
        }
        if (message.indexOf('timeout') != -1) {
          message = '请求超时，请重新再试'
          istimeOut = true
        } else if (message.indexOf('Network Error') != -1) {
          message = '网络连接错误，请稍后再试'
          istimeOut = true
        } else {
          istimeOut = false
        }
        // console.log(message, statusCode, tip)
        showMessageBox(message, statusCode, tip, istimeOut)
      }
      return Promise.reject(error)
    }
  )
}

export default service
